
import axios from 'axios'

export default {
  namespaced: true,
  state () {
    return {
      list: []
    }
  },
  mutations: {
    updateList (state, newList) {
      state.list = newList
    },
    updateItem (state, item) {
      console.log(item)
      const itemInList = state.list.find(itemTmp => itemTmp.id === item.id)
      if (itemInList === undefined) {
        console.log('updateItem() cant find item', item.id)
        return
      }
      itemInList.name = item.name
      itemInList.price = item.price
      itemInList.count = item.count
      itemInList.thumb = item.thumb
    }
  },
  actions: {
    async asyncUpdateListFromSrv (context) {
      const res = await axios.get('http://localhost:3000/cart')
      console.log(res)
      context.commit('updateList', res.data)
    },
    async asyncUpdateItemToSrv (context, item) {
      const res = await axios.patch(`http://localhost:3000/cart/${item.id}`, { count: item.count })
      if (res.status !== 200) {
        console.log('asyncUpdateItemToSrv failed', res)
        return
      }

      // 更新 vuex中数据
      context.commit('updateItem', item)
    }
  },
  getters: {}
}
